package org.fingersnow.dbdictionary;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.fingersnow.dbdictionary.dto.DataBase;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 *  	将模板转成word文件
 * @author dingy
 */
public class Template2Word {

	private String modelFileName = "model.ftl"; 
	private String outPutFilePathName = "outFile" + Math.random() * 10000 + ".docx";
	private DataBase dataBase;
	
	public Template2Word(String modelFileName, String outPutFilePathName,DataBase dataBase) {
		this.dataBase = dataBase;
		if(null != modelFileName && !"".equals(modelFileName)) {
			this.modelFileName = modelFileName;
		}
		if(null != outPutFilePathName && !"".equals(outPutFilePathName)) {
			this.outPutFilePathName = outPutFilePathName;
		}
	}
	
	public void templateToCreateWord() throws URISyntaxException, IOException, TemplateException {
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		URL resource = Thread.currentThread().getContextClassLoader().getResource("ftl");
		File templatesDir = new File(resource.toURI());
		cfg.setDirectoryForTemplateLoading(templatesDir);
		// 设置默认字符集
		cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
		// 设置出现异常处理的方式，开发阶段可以设置为HTML_DEBUG_HANDLER
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
		cfg.setLogTemplateExceptions(false);
		cfg.setWrapUncheckedExceptions(true);

		Template template = cfg.getTemplate(modelFileName);
		File outFile = new File(outPutFilePathName); // 导出文件
		Writer out = null;
		out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
		template.process(dataBase, out);
		out.flush();
		if (null != out) {
			out.close();
		}
	}
	
}
